import {
    login,
    regis_company,
    regis_person,
    getinformation,
    userlogout,
    getMinegoods,
    getcart_list,
    getquote_list, getPowers
} from '@/network/api/user.js'
import order from './order.js'

let quote = uni.getStorageSync('quote')
let user = uni.getStorageSync('user')
let maininfo = uni.getStorageSync('maininfo')
const state = {
    mygoodsnum: uni.getStorageSync('mygoodsnum') || 0,
    cart: [], // 购物车
    quote: quote || [], //报价车
    cartnums: uni.getStorageSync('cartnums') || 0,
    quotenums: uni.getStorageSync('quotenums') || 0,
    limit_amount: 0, // 单笔限制金额
    limit_month: 0, // 月限制金额
    islogin: user ? true : false, // 是否登录
    company: user.company || {}, // 用户公司信息
    userinfo: user.userinfo || {}, // 用户个人信息
    character_id: null, // 用户角色
    power: user.power || [], // 用户权限
    maininfo: maininfo || {},
}
const getters = {}

const actions = {
    getPowerslist({commit, state}) {
        if (state.islogin) {
            getPowers().then(res => {
                commit('setPower', res.data)
            })
        }
    },
    async getCart({
                      commit,
                      state
                  }) { // 获取购物车
        if (state.islogin) { // 判断是否登录
            const res = await getcart_list()
            console.log(res);
            if (res.data.code == 1) {

                commit("setCart", res.data)
            }

        }
    },
    async getQuoteCart({
                           commit,
                           state
                       }) { // 获取报价车
        if (state.islogin) {
            const res = await getquote_list()
            if (res.data.code == 1) {
                commit("setquotacart", res.data)
            }
        }
    },
    //获取个人商品
    async getusergoods({
                           state,
                           commit
                       }, arg) {
        let data = {
            id: '',
            brand: '',
            sort: '',
            page: 1,
            search: '',
            successively: '',
            company_id: state.userinfo.company_id
        }
        if (state.islogin) {
            // 转圈
            uni.showLoading({
                    title: '加载中',
                }
            )
            const res = await getMinegoods(data)
            uni.hideLoading()
            commit("setusergoods", res.data)
        }
    },
     logout({
                     state,
                     commit
                 }) {
        uni.showModal({
            title: '提示',
            content: '確定退出登錄？',
            success: async function (res) {
                if (res.confirm) {
                    uni.clearStorageSync()
                    uni.removeStorageSync('mygoodsnum')
                    commit("setlogout");
                    uni.reLaunch({
                        url: '/pages/mine/index'
                    })
                    const res = await userlogout()
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
            }
        });



        //uniapp是否退出登录弹窗提示代码？



    },
    async getCenterMainInfo({
                                state,
                                commit
                            }) { // 获取首页管理个人信息
        if (state.islogin) {
            const res = await getinformation()
            if (res.data.code == 1) {
                commit("setCenterMainInfo", res.data)
                uni.setStorageSync('maininfo', res.data)
            }
        }
    },
    async sendLogin({
                        state,
                        commit,
                        dispatch
                    }, arg) {
        // if (state.islogin) return;
        const res = await login(arg)
        if (res.data.code == 1) {
            console.log(res);
            commit("setLogin", res.data);
            uni.setStorageSync('user', res.data)
            dispatch("getCart") // 获取购物车
            dispatch("getQuoteCart")
            dispatch("getCenterMainInfo")
            dispatch("getusergoods")
            uni.showToast({
                title: '登录成功',
                icon: 'success', //将值设置为 success 或者 ''
                duration: 2000 //持续时间为 2秒
            }) // 获取购物车// 获取报价车
            uni.switchTab({
                url: '/pages/mine/index'
            })
        } else {
            uni.showToast({
                title: res.data.msg,
                icon: 'none', //如果要纯文本，不要icon，将值设为'none'
                duration: 2000 //持续时间为 2秒
            })

        }
    } // 登录请求
    ,
    //公司用户
    async regiscompany({
                           state,
                           commit
                       }, arg) {
        let {
            username,
            companyname,
            en_companyname,
            password,
            email,
            consignee,
            mobile,
            fax,
            address,
            area,
            industry,
            market,
            license
        } = arg
        let data = {
            username,
            password,
            companyname,
            en_companyname,
            email,
            consignee,
            mobile,
            fax,
            address,
            area,
            industry,
            market,
            license
        }
        //转圈
        uni.showLoading({
                title: '注册中',
            }
        )
        const res = await regis_company(data)
        uni.hideLoading()
        if (res.data.code == 1) {
            uni.showToast({
                title: '注册成功',
            })
            //一秒返回
            setTimeout(function () {
                uni.navigateBack({
                    delta: 1
                })
            }, 1000);
        } else if (res.data.msg) {
            uni.showToast({
                title: res.data.msg,
                icon: 'none', //如果要纯文本，不要icon，将值设为'none'
                duration: 2000 //持续时间为 2秒
            })
        }

    },
    //个人用户
    async regisperson({
                          state,
                          commit
                      }, arg) {
        if (state.islogin) return;
        let {
            username,
            password,
            email,
            consignee,
            mobile,
            address
        } = arg;
        let data = {
            username,
            password,
            email,
            consignee,
            mobile,
            address
        }
        //转圈
        uni.showLoading({
                title: '注册中',
            }
        )
        const res = await regis_person(data)
        uni.hideLoading()
        if (res.data.code == 1) {
            uni.showToast({
                title: '注册成功',
            })
            //一秒返回
            setTimeout(function () {
                    uni.navigateBack({
                        delta: 1
                    })
                }
                , 1000);
        } else if (res.data.msg) {
            uni.showToast({
                title: res.data.msg,
                icon: 'none', //如果要纯文本，不要icon，将值设为'none'
                duration: 2000 //持续时间为 2秒
            })
        }
    }
}
const mutations = {
    setPower(state, arg) {
    },
    setusergoods(state, arg) {
        console.log(arg, '123wwww');
        state.mygoodsnum = arg.personal.total
        uni.setStorageSync('mygoodsnum', state.mygoodsnum)
    },
    setquotacart(state, arg) {
        console.log(arg, '123');
        state.quote = arg.quote
        state.quotenums = arg.quote.reduce((total, item) => total + item.goods_number, 0);
        uni.setStorageSync('quotenums', state.quotenums)
        uni.setStorageSync('quote', arg.quote)
    },
    setCart(state, arg) {
        state.cart = arg.cart;
        state.cartnums = arg.cart.reduce((total, item) => total + item.goods_number, 0);
        uni.setStorageSync('cartnums', state.cartnums)
        state.limit_amount = arg.limit_amount;
        state.limit_month = arg.month;
    },
    setlogout(state, arg) {
        state.islogin = false
        state.company = {};
        state.userinfo = {};
        state.character_id = '';
        state.power = [];
        state.maininfo = {};
        state.mygoodsnum = 0;
        state.cart = [];
        state.quote = [];
        state.cartnums = 0;
    },
    setLogin(state, arg) { // 写入登录用户信息
        let {
            company,
            userinfo,
            power
        } = arg;
        state.islogin = true
        state.company = company;
        state.userinfo = userinfo;
        state.character_id = userinfo.character_id;
        state.power = power;
    },
    setCenterMainInfo(state, arg) { // 写入首页管理个人信息
        // console.log(arg)
        state.maininfo = {
            user: arg.user,
            company: arg.company,
            order: {
                cart: arg.cart,
                collection: arg.collection,
                order: arg.order,
                quote: arg.quote,
                mine_order: arg.mine_order,
                other_order: arg.other_order,

            }
        }
    },
}

export default {
    state,
    actions,
    getters,
    mutations
}
